package com.sengled.cloud.biz.union.mgt.service.sys.impl;

import com.sengled.cloud.biz.union.mgt.common.CommonConstant;
import com.sengled.cloud.biz.union.mgt.common.PageUtil;
import com.sengled.cloud.biz.union.mgt.common.util.Md5Util;
import com.sengled.cloud.biz.union.mgt.dao.sys.*;
import com.sengled.cloud.biz.union.mgt.model.enums.AccountStatusEnum;
import com.sengled.cloud.biz.union.mgt.model.po.*;
import com.sengled.cloud.biz.union.mgt.model.request.SaveShopAccountRequest;
import com.sengled.cloud.biz.union.mgt.model.request.ShopAccountRequest;
import com.sengled.cloud.biz.union.mgt.model.response.*;
import com.sengled.cloud.biz.union.mgt.model.vo.*;
import com.sengled.cloud.biz.union.mgt.service.sys.IShopAccountService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by chenshuai on 2017/11/15.
 */
@Service("shopAccountServiceImpl")
public class ShopAccountServiceImpl implements IShopAccountService {

    @Autowired
    private ShopAccountDao shopAccountDao;
    @Autowired
    private ModuleDao moduleDao;
    @Autowired
    private ShopAccountModuleDao shopAccountModuleDao;
    @Autowired
    private UserAccountDao userAccountDao;
    @Autowired
    private UserAcctShopAcctDao userAcctShopAcctDao;

    @Override
    public ResponseMessage<ShopAccountPage> listShopAccountByPage(ShopAccountRequest shopAccountRequest,Long accountId) {
        ResponseMessage<ShopAccountPage> rm = new ResponseMessage<ShopAccountPage>();
        try {
            ShopAccount shopAccount = new ShopAccount();
            if(shopAccountRequest != null){
                shopAccount.setShopCode(shopAccountRequest.getShopCode());
                shopAccount.setShopName(shopAccountRequest.getShopName());
            }

            UserAccount userAccount = userAccountDao.selectByPrimaryKey(accountId);

            if(userAccount != null && userAccount.getCompanyId() != null){
                Long i = userAccount.getInt001();
                if(i != null){
                    //是超级用户
                    Long companyId = userAccount.getCompanyId();
                    shopAccount.setCompanyId(companyId);
                    int rowCount = shopAccountDao.queryShopAccountCount(shopAccount);
                    if(rowCount > 0){
                        PageUtil pageUtil = new PageUtil(shopAccountRequest.getCurrentPage(), CommonConstant.PageConstant.PAGE_SIZE ,rowCount);

                        List<ShopAccount> shopAccounts = shopAccountDao.listShopAccount(shopAccount,pageUtil);
                        List<ShopAccountWithStatus> shopAccountWithStatuses = new ArrayList<ShopAccountWithStatus>();
                        shopAccounts.forEach(s -> {
                            ShopAccountWithStatus shopAccountWithStatus =  new ShopAccountWithStatus();
                            //账户状态: 1 在线、2 离线、3 锁定、4 失效
                            shopAccountWithStatus.setId(s.getId());
                            shopAccountWithStatus.setName(s.getShopName());
                            shopAccountWithStatus.setCode(s.getShopCode());
                            shopAccountWithStatus.setPadLoginName(s.getShopCode());
                            shopAccountWithStatus.setStatus(AccountStatusEnum.ACCOUNT_STATUS_INVALID.getValueByKey(s.getAccountStatus()));
                            shopAccountWithStatuses.add(shopAccountWithStatus);
                        });
                        ShopAccountPage shopAccountPage = new ShopAccountPage();
                        shopAccountPage.setPage(pageUtil);
                        shopAccountPage.setShopAccountWithStatusList(shopAccountWithStatuses);
                        rm.setData(shopAccountPage);
                        return rm;
                    }else{
                        //登录角色公司id为空
                        rm.buildParamErrorMessage();
                        return rm;
                    }
                }else{
                    //不是超级用户，只显示有权限的店铺账号
                    int rowCount = userAcctShopAcctDao.queryUserAcctShopAcctCountByUserKey(accountId);
                    if(rowCount > 0){
                        PageUtil pageUtil = new PageUtil(shopAccountRequest.getCurrentPage(), CommonConstant.PageConstant.PAGE_SIZE ,rowCount);
                        List<ShopAccount> shopAccounts = userAcctShopAcctDao.listShopAccount(accountId,pageUtil);
                        List<ShopAccountWithStatus> shopAccountWithStatuses = new ArrayList<ShopAccountWithStatus>();
                        shopAccounts.forEach(s -> {
                            ShopAccountWithStatus shopAccountWithStatus =  new ShopAccountWithStatus();
                            //账户状态: 1 在线、2 离线、3 锁定、4 失效
                            shopAccountWithStatus.setId(s.getId());
                            shopAccountWithStatus.setName(s.getShopName());
                            shopAccountWithStatus.setCode(s.getShopCode());
                            shopAccountWithStatus.setPadLoginName(s.getShopCode());
                            shopAccountWithStatus.setStatus(AccountStatusEnum.ACCOUNT_STATUS_INVALID.getValueByKey(s.getAccountStatus()));
                            shopAccountWithStatuses.add(shopAccountWithStatus);
                        });
                        ShopAccountPage shopAccountPage = new ShopAccountPage();
                        shopAccountPage.setPage(pageUtil);
                        shopAccountPage.setShopAccountWithStatusList(shopAccountWithStatuses);
                        rm.setData(shopAccountPage);
                        return rm;
                    }else{
                        return rm;
                    }
                }
                }else{
                return rm;
            }

        }catch (Exception e){
            rm.buildSystemErrorMessage();
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public ResponseMessage<ShopAccountResponse> editShopAccount(Long id) {
        ResponseMessage<ShopAccountResponse> rm = new ResponseMessage<ShopAccountResponse>();
        try {

            ShopAccountResponse shopAccountResponse = new ShopAccountResponse();
            ShopAccountWithStatus shopAccountWithStatus = new ShopAccountWithStatus();
            ShopAccount shopAccount = new ShopAccount();
            shopAccount.setId(id);
            List<ShopAccount> shopAccounts = shopAccountDao.listShopAccount(shopAccount,null);
            if(CollectionUtils.isNotEmpty(shopAccounts)){
                shopAccount = shopAccounts.get(0);
            }

            shopAccountWithStatus.setCode(shopAccount.getShopCode());
            shopAccountWithStatus.setName(shopAccount.getShopName());
            shopAccountWithStatus.setId(shopAccount.getId());
            shopAccountWithStatus.setPadLoginName(shopAccount.getShopCode());
            shopAccountWithStatus.setStatus(AccountStatusEnum.ACCOUNT_STATUS_INVALID.getValueByKey(shopAccount.getAccountStatus()));

            List<ModuleWithChecked> moduleWithCheckeds = moduleDao.selectPadModule(0L);
            List<ShopAccountModule> shopAccountModules = shopAccountModuleDao.selectShopAccountModuleList(shopAccount.getId());
            Map<Long,Long> checkedMap = shopAccountModules.stream().collect(Collectors.toMap(ShopAccountModule::getModuleId,ShopAccountModule::getModuleId));
            moduleWithCheckeds = this.getIteratPadModuleWithChecked(moduleWithCheckeds,checkedMap);

            Map<Long,Integer> pcMap = new HashMap();
            pcMap.put(15L,3);
            pcMap.put(26L,2);
            pcMap.put(29L,3);
            moduleWithCheckeds.forEach(moduleWithChecked -> {
                List<ModuleWithChecked> child = moduleWithChecked.getChildModules().stream().filter((mpwc) -> mpwc.isChecked() == true).collect(Collectors.toList());
                if(child != null  && child.size()< pcMap.get(moduleWithChecked.getId())){
                    moduleWithChecked.setChecked(false);
                }
            });

            shopAccountResponse.setShopAccountWithStatus(shopAccountWithStatus);
            shopAccountResponse.setModuleWithCheckeds(moduleWithCheckeds);
            rm.setData(shopAccountResponse);

            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public ResponseMessage<ShopAccountResponse> shopAccountDetail(Long id) {
        ResponseMessage<ShopAccountResponse> rm = new ResponseMessage<ShopAccountResponse>();
        try {

            ShopAccountResponse shopAccountResponse = new ShopAccountResponse();
            ShopAccountWithStatus shopAccountWithStatus = new ShopAccountWithStatus();
            ShopAccount shopAccount = new ShopAccount();
            shopAccount.setId(id);
            List<ShopAccount> shopAccounts = shopAccountDao.listShopAccount(shopAccount,null);
            if(CollectionUtils.isNotEmpty(shopAccounts)){
                shopAccount = shopAccounts.get(0);
            }

            shopAccountWithStatus.setCode(shopAccount.getShopCode());
            shopAccountWithStatus.setName(shopAccount.getShopName());
            shopAccountWithStatus.setId(shopAccount.getId());
            shopAccountWithStatus.setPadLoginName(shopAccount.getShopCode());
            shopAccountWithStatus.setStatus(AccountStatusEnum.ACCOUNT_STATUS_INVALID.getValueByKey(shopAccount.getAccountStatus()));

            List<ModuleWithChecked> moduleWithCheckeds = moduleDao.selectPadModule(0L);
            List<ShopAccountModule> shopAccountModules = shopAccountModuleDao.selectShopAccountModuleList(shopAccount.getId());
            Map<Long,Long> checkedMap = shopAccountModules.stream().collect(Collectors.toMap(ShopAccountModule::getModuleId,ShopAccountModule::getModuleId));
            moduleWithCheckeds = this.getIteratPadModuleWithChecked(moduleWithCheckeds,checkedMap);

            moduleWithCheckeds.forEach(moduleWithChecked -> {
                List<ModuleWithChecked> child = moduleWithChecked.getChildModules().stream().filter((mpwc) -> mpwc.isChecked() == true).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(child)){
                    moduleWithChecked.setChecked(true);
                }
            });

            shopAccountResponse.setShopAccountWithStatus(shopAccountWithStatus);
            shopAccountResponse.setModuleWithCheckeds(moduleWithCheckeds);
            rm.setData(shopAccountResponse);

            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            e.printStackTrace();
            return rm;
        }
    }

    private List<ModuleWithChecked> getIteratPadModuleWithChecked(List<ModuleWithChecked> moduleWithCheckeds,Map<Long,Long> checkedMap){
        if(CollectionUtils.isNotEmpty(moduleWithCheckeds)){
            moduleWithCheckeds.forEach(moduleWithChecked -> {
                if(checkedMap.containsKey(moduleWithChecked.getId())){
                    moduleWithChecked.setChecked(true);
                }
                List<ModuleWithChecked> childModules = moduleDao.selectPadModule(moduleWithChecked.getId());
                if(CollectionUtils.isNotEmpty(childModules)){
                    moduleWithChecked.setChildModules(childModules);
                    this.getIteratPadModuleWithChecked(childModules,checkedMap);
                }
            });
        }
        return moduleWithCheckeds;
    }

    @Override
    public ResponseMessage saveShopAccount(SaveShopAccountRequest saveShopAccountRequest) {
        ResponseMessage rm = new ResponseMessage();
        try{
            Long shopAccountId = saveShopAccountRequest.getShopAccountId();
            List<Long> moduleIds = saveShopAccountRequest.getModuleIds();

            if(CollectionUtils.isNotEmpty(moduleIds)){
            List<Long> pModuleIds = moduleDao.selectParentIdByModuleId(moduleIds).stream().distinct().collect(Collectors.toList());

            //前端不传主节点ID
            pModuleIds.forEach(p -> {
                if(p>0 && !moduleIds.contains(p)){
                    moduleIds.add(p);
                }
            });
            //自己判断
                shopAccountModuleDao.deleteByShopAccountKey(shopAccountId);
                shopAccountModuleDao.batchInsert(shopAccountId,moduleIds);
            }else{
                shopAccountModuleDao.deleteByShopAccountKey(shopAccountId);
            }
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            e.printStackTrace();
            return rm;
        }
    }

    @Override
    public ResponseMessage resetPwd(Long id, String newPwd) {
        ResponseMessage rm = new ResponseMessage();
        try{
            ShopAccount shopAccount = new ShopAccount();
            shopAccount.setId(id);
            newPwd = Md5Util.md5(newPwd);
            shopAccount.setAccountPwd(newPwd);
            shopAccountDao.updateByPrimaryKey(shopAccount);
            return rm;
        }catch (Exception e){
            rm.buildSystemErrorMessage();
            return rm;
        }
    }
}
